/**
 * 投稿API处理
 */

import { Database } from '../db/database.js';

// 处理投稿相关的API请求
export async function handleSubmissionAPI(request, env) {
  try {
    const url = new URL(request.url);
    const path = url.pathname;
    const method = request.method;
    const db = new Database(env);
    
    // 解析请求体
    let requestBody = null;
    if (method === 'POST' || method === 'PUT') {
      try {
        requestBody = await request.json();
      } catch (jsonError) {
        return new Response(JSON.stringify({
          error: '无效的JSON格式'
        }), {
          status: 400,
          headers: {
            'Content-Type': 'application/json'
          }
        });
      }
    }
    
    // API路由处理
    
    // 创建新投稿
    if (path === '/api/submissions' && method === 'POST') {
      return await createSubmission(requestBody, db);
    }
    
    // 获取投稿列表
    if (path === '/api/submissions' && method === 'GET') {
      const page = parseInt(url.searchParams.get('page') || '1');
      const limit = parseInt(url.searchParams.get('limit') || '20');
      const status = url.searchParams.has('status') ? parseInt(url.searchParams.get('status')) : null;
      
      return await getSubmissions(page, limit, status, db);
    }
    
    // 获取单个投稿
    if (path.match(/^\/api\/submissions\/\d+$/) && method === 'GET') {
      const id = parseInt(path.split('/').pop());
      return await getSubmissionById(id, db);
    }
    
    // 更新投稿状态
    if (path.match(/^\/api\/submissions\/\d+\/status$/) && method === 'PUT') {
      const id = parseInt(path.split('/')[3]);
      const status = requestBody?.status;
      
      if (status === undefined || status === null) {
        return new Response(JSON.stringify({
          error: '状态参数不能为空'
        }), {
          status: 400,
          headers: {
            'Content-Type': 'application/json'
          }
        });
      }
      
      return await updateSubmissionStatus(id, status, db);
    }
    
    // 删除投稿
    if (path.match(/^\/api\/submissions\/\d+$/) && method === 'DELETE') {
      const id = parseInt(path.split('/').pop());
      return await deleteSubmission(id, db);
    }
    
    // 未匹配的路由
    return new Response(JSON.stringify({
      error: 'API路由不存在',
      path: path
    }), {
      status: 404,
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
  } catch (error) {
    console.error('API处理错误:', error);
    return new Response(JSON.stringify({
      error: '服务器内部错误',
      message: error.message || '未知错误'
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
}

// 创建新投稿
async function createSubmission(data, db) {
  try {
    // 验证必填字段
    const requiredFields = ['grade', 'class', 'name', 'title', 'category', 'content'];
    const missingFields = requiredFields.filter(field => !(field in data));
    
    if (missingFields.length > 0) {
      return new Response(JSON.stringify({
        error: '缺少必填字段',
        missing: missingFields
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    // 验证年级范围（1-9）
    const grade = parseInt(data.grade);
    if (isNaN(grade) || grade < 1 || grade > 9) {
      return new Response(JSON.stringify({
        error: '年级必须在1-9之间'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    // 验证班级范围（1-5）
    const classValue = parseInt(data.class);
    if (isNaN(classValue) || classValue < 1 || classValue > 5) {
      return new Response(JSON.stringify({
        error: '班级必须在1-5之间'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    // 验证分类范围（1-6）
    const category = parseInt(data.category);
    if (isNaN(category) || category < 1 || category > 6) {
      return new Response(JSON.stringify({
        error: '分类必须在1-6之间'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    // 清理和验证字符串字段
    const name = data.name.trim();
    const title = data.title.trim();
    const content = data.content.trim();
    
    if (name.length === 0) {
      return new Response(JSON.stringify({
        error: '姓名不能为空'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    if (title.length === 0) {
      return new Response(JSON.stringify({
        error: '标题不能为空'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    if (content.length === 0) {
      return new Response(JSON.stringify({
        error: '内容不能为空'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    // 添加投稿到数据库
    const submissionData = {
      grade,
      class: classValue,
      name,
      title,
      category,
      content
    };
    
    const id = await db.addSubmission(submissionData);
    
    return new Response(JSON.stringify({
      success: true,
      id,
      message: '投稿成功'
    }), {
      status: 201,
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
  } catch (error) {
    console.error('创建投稿失败:', error);
    return new Response(JSON.stringify({
      error: '创建投稿失败',
      message: error.message || '未知错误'
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
}

// 获取投稿列表
async function getSubmissions(page, limit, status, db) {
  try {
    // 验证分页参数
    if (isNaN(page) || page < 1) page = 1;
    if (isNaN(limit) || limit < 1 || limit > 100) limit = 20;
    
    const result = await db.getSubmissions(page, limit, status);
    
    return new Response(JSON.stringify({
      success: true,
      data: result.submissions,
      pagination: {
        total: result.total,
        page: result.page,
        limit: result.limit,
        totalPages: result.totalPages
      }
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
  } catch (error) {
    console.error('获取投稿列表失败:', error);
    return new Response(JSON.stringify({
      error: '获取投稿列表失败',
      message: error.message || '未知错误'
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
}

// 获取单个投稿
async function getSubmissionById(id, db) {
  try {
    if (isNaN(id) || id < 1) {
      return new Response(JSON.stringify({
        error: '无效的投稿ID'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    const submission = await db.getSubmissionById(id);
    
    if (!submission) {
      return new Response(JSON.stringify({
        error: '投稿不存在'
      }), {
        status: 404,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    return new Response(JSON.stringify({
      success: true,
      data: submission
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
  } catch (error) {
    console.error('获取投稿详情失败:', error);
    return new Response(JSON.stringify({
      error: '获取投稿详情失败',
      message: error.message || '未知错误'
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
}

// 更新投稿状态
async function updateSubmissionStatus(id, status, db) {
  try {
    if (isNaN(id) || id < 1) {
      return new Response(JSON.stringify({
        error: '无效的投稿ID'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    // 验证状态值（0: 待审核, 1: 已通过, 2: 已拒绝）
    if (![0, 1, 2].includes(parseInt(status))) {
      return new Response(JSON.stringify({
        error: '无效的状态值，必须是0（待审核）、1（已通过）或2（已拒绝）'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    const success = await db.updateSubmissionStatus(id, parseInt(status));
    
    if (!success) {
      return new Response(JSON.stringify({
        error: '投稿不存在或更新失败'
      }), {
        status: 404,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    return new Response(JSON.stringify({
      success: true,
      message: '状态更新成功'
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
  } catch (error) {
    console.error('更新投稿状态失败:', error);
    return new Response(JSON.stringify({
      error: '更新投稿状态失败',
      message: error.message || '未知错误'
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
}

// 删除投稿（实现为软删除）
async function deleteSubmission(id, db) {
  try {
    if (isNaN(id) || id < 1) {
      return new Response(JSON.stringify({
        error: '无效的投稿ID'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    // 使用软删除方法，标记为已删除而不是真正删除
    const success = await db.softDeleteSubmission(id);
    
    if (!success) {
      return new Response(JSON.stringify({
        error: '投稿不存在或已被删除'
      }), {
        status: 404,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    return new Response(JSON.stringify({
      success: true,
      message: '投稿已成功删除（软删除）'
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
  } catch (error) {
    console.error('删除投稿失败:', error);
    return new Response(JSON.stringify({
      error: '删除投稿失败',
      message: error.message || '未知错误'
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
}